import View from '@/components/View'
import React, { FC, useState } from 'react'
import { Button, DatePicker, Form, Input, message, Modal, Popconfirm, Select, Table, Tooltip } from 'antd'
import { DeleteOutlined, FormOutlined, PlusOutlined } from '@ant-design/icons'
import { useAntdTable, useBoolean, useRequest } from 'ahooks'
import { getUserData } from '@/hooks/auth/user'
import { addUserApi, deleteUserApi, updateUserApi } from '@/api/auth/user'
import './index.scss'

// userForm配置
const userFormConfig = [
  { label: '登录名', name: 'loginName', rules: [{ required: true, message: '请输入内容' }] },
  { label: '昵称', name: 'nickName', rules: [{ required: true, message: '请输入内容' }] },
  { label: '密码', name: 'password', rules: [{ required: true, message: '请输入内容' }] },
  { label: '密保邮箱', name: 'protectEmail', rules: [{ required: true, message: '请输入内容' }] },
  { label: '密码手机', name: 'protectPhone', rules: [{ required: true, message: '请输入内容' }] },
]
// 创建FormItem
const getUserFormItem = () => {
  const children = []
  userFormConfig.forEach((item, index) => {
    children.push(
      <Form.Item key={index} label={item.label} name={item.name} rules={item.rules}>
        <Input />
      </Form.Item>,
    )
  })
  return children
}

const AuthUser:FC = () => {
  // 获取表单实例
  const [tableForm] = Form.useForm()
  const [userForm] = Form.useForm()
  const { Option } = Select
  // 弹窗标题、控制、加载变量
  const [modalTitle, setModalTitle] = useState<string>('创建用户')
  const [visible, { setTrue, setFalse }] = useBoolean(false)
  const [userId, setUserId] = useState<number>(null)
  // ahooks定义表格数据和方法
  const { tableProps, search } = useAntdTable(getUserData, {
    defaultPageSize: 10,
    form: tableForm,
  })
  // 表单重置和搜索方法
  const { submit, reset } = search

  /**
   * 用户操作接口模块
   */

  // 添加用户接口
  const { run: addRun, loading: addLoading } = useRequest(addUserApi, {
    manual: true,
    onSuccess: () => {
      message.success('创建用户成功')
      setFalse()
      reset()
    },
  })
  // 修改用户接口
  const { run: updateRun, loading: updateLoading } = useRequest(updateUserApi, {
    manual: true,
    onSuccess: () => {
      message.success('修改用户成功')
      setFalse()
      reset()
    },
  })
  // 删除用户接口
  const { run: delRun } = useRequest(deleteUserApi, {
    manual: true,
    onSuccess: () => {
      message.success('删除用户成功！')
      reset()
    },
  })
  // 判断Modal的loading
  const getLoadingVar = () => {
    switch (modalTitle) {
      case '创建用户':
        return addLoading
      case '修改用户':
        return updateLoading
      default:
        return null
    }
  }
  const addUserModal = () => {
    setModalTitle('创建用户')
    userForm.resetFields()
    setTrue()
  }
  const updateUserModal = (params) => {
    setUserId(params.id)
    setModalTitle('修改用户')
    userForm.setFieldsValue(params)
    setTrue()
  }
  const submitUserForm = () => {
    userForm.validateFields().then((values) => {
      switch (modalTitle) {
        case '创建用户':
          addRun(values)
          break
        case '修改用户':
          updateRun(userId, values)
          break
        default:
          break
      }
    })
  }
  const columns = [
    {
      title: '登录名',
      dataIndex: 'loginName',
      key: 'loginName',
      width: 100,
      ellipsis: true,
    },
    {
      title: '昵称',
      dataIndex: 'nickName',
      key: 'nickName',
      width: 150,
      ellipsis: true,
    },
    {
      title: '账号状态',
      dataIndex: 'isLockout',
      key: 'isLockout',
      width: 100,
      align: 'center' as 'center',
      render: (text) => {
        if (text) {
          return (<span style={{ color: 'red' }}>已锁定</span>)
        }
        return (<span style={{ color: 'green' }}>正常</span>)
      },
    },
    {
      title: '密保邮箱',
      dataIndex: 'protectEmail',
      key: 'protectEmail',
      width: 150,
    },
    {
      title: '密保手机',
      dataIndex: 'protectPhone',
      key: 'protectPhone',
      width: 120,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 200,
      align: 'center' as 'center',
    },
    {
      title: '操作',
      dataIndex: '',
      key: 'action',
      className: 'aciton-th',
      width: 120,
      align: 'center' as 'center',
      fixed: 'right' as 'right',
      render: (text, record) => (
        <div className="button-box">
          <Tooltip title="编辑">
            <Button
              shape="circle"
              style={{ marginRight: '5px' }}
              type="primary"
              onClick={() => updateUserModal(record)}
              icon={<FormOutlined />}
            />
          </Tooltip>
          <Popconfirm
            placement="topRight"
            title={<span>是否确认删除用户<span style={{ color: 'red' }}>{record.nickName}</span></span>}
            onConfirm={() => delRun(record.id)}
            okText="确认"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <Button type="primary" shape="circle" danger icon={<DeleteOutlined />} />
            </Tooltip>
          </Popconfirm>
        </div>
      ),
    },
  ]
  return (
    <View className="app-auth-user">
      <div className="filter-form">
        <Form
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
          name="user-search-form"
          form={tableForm}
        >
          <Form.Item label="登录名" name="loginName">
            <Input />
          </Form.Item>
          <Form.Item label="昵称" name="nickName">
            <Input />
          </Form.Item>
          <Form.Item label="账号状态" name="isLockout">
            <Select>
              <Option value="0">正常</Option>
              <Option value="1">已锁定</Option>
            </Select>
          </Form.Item>
          <Form.Item label="密保邮箱" name="protectEmail">
            <Input />
          </Form.Item>
          <Form.Item label="密保手机" name="protectPhone">
            <Input />
          </Form.Item>
          <Form.Item label="创建时间" name="createTimeStart">
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item>
            <Button type="primary" onClick={submit}>搜索</Button>
            <Button onClick={reset} style={{ marginLeft: 10 }}>重置</Button>
          </Form.Item>
        </Form>
      </div>
      <div className="user-top-bar">
        <Button type="primary" icon={<PlusOutlined />} onClick={addUserModal}>创建用户</Button>
      </div>
      <div className="user-table">
        <Table columns={columns} rowKey={(record) => record.id} {...tableProps} />
      </div>
      <Modal
        title={modalTitle}
        visible={visible}
        confirmLoading={getLoadingVar()}
        onOk={submitUserForm}
        onCancel={setFalse}
        width={400}
      >
        <Form
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 18 }}
          name="user-item-form"
          form={userForm}
        >
          {getUserFormItem}
        </Form>
      </Modal>
    </View>
  )
}

export default AuthUser
